package test.org.offsync.nio

import java.nio.channels.{SelectionKey => JavaSelectionKey}
import org.junit.runner.RunWith
import org.offsync.async.DeadlineTimer
import org.offsync.async.AsyncSelector
import org.offsync.rich._
import org.offsync.util.Duration
import org.offsync.util.Time
import scala.collection.mutable.ListBuffer

import scala.actors.Future

@RunWith(classOf[org.specs2.runner.JUnitRunner])
class SpecDeadlineTimer extends org.specs2.mutable.SpecificationWithJUnit {
  override def intToRichLong(v: Int) = super.intToRichLong(v)
  override def longToRichLong(v: Long) = super.longToRichLong(v)
  
  "Selector" should {
    val selector = new AsyncSelector()
    val deadlineTimer = new DeadlineTimer()
    "execute deadline timer code at correct time" in {
      var time0 = Time.zero
      var time1 = Time.zero
      var time2 = Time.zero
      time0 = Time.now
      deadlineTimer.execute(2.seconds.from(Time.now)) {
        selector.execute {
          time1 = Time.now
          selector.dispose()
        }
      }
      
      time2 = Time.now
      Thread.sleep(3000)
      deadlineTimer.dispose()
      (time1 - time0).roundTo(200.millis) must_== 2.seconds
      (time2 - time0).roundTo(200.millis) must_== 0.seconds
    }
  }
}
